package com.sam.security.util;

import java.security.MessageDigest;

import org.springframework.security.providers.encoding.PlaintextPasswordEncoder;

/**
 * 兼容eMan系统对密码进行md5加密.
 * 
 * @author Sam
 */
public class MD5PasswordEncoder extends PlaintextPasswordEncoder {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.providers.encoding.PlaintextPasswordEncoder#isPasswordValid(java.lang.String,
	 *      java.lang.String, java.lang.Object)
	 */
	@Override
	public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
		String pass2 = mergePasswordAndSalt(rawPass, salt, false);

		if (!super.isIgnorePasswordCase()) {
			return encPass.equals(pass2) || encode(encPass).equals(rawPass)
					|| encPass.equals(encode(rawPass));
		} else {
			return encPass.equalsIgnoreCase(pass2)
					|| encode(encPass.toLowerCase()).equals(
							rawPass.toLowerCase())
					|| encPass.toLowerCase().equals(
							encode(rawPass.toLowerCase()));
		}
	}

	/**
	 * Encode.
	 * 
	 * @param s
	 *            the s
	 * 
	 * @return the string
	 */
	public static String encode(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

}
